package com.aaa.jwt;

import io.jsonwebtoken.*;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 封装解析token
 */
@Component
public class JwtTokenUtils {
    public static void main(String[] args) {
       Claims claims=getToken("eyJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJhYWEiLCJleHAiOjE2MjI0Mjk5MDUsImlhdCI6MTYyMjQyNjMwNSwiYXV0aCI6eyJhdXRob3JpdGllcyI6W3siYXV0aG9yaXR5IjoiUk9MRV9BRE1JTiJ9XSwiZGV0YWlscyI6eyJyZW1vdGVBZGRyZXNzIjoiMDowOjA6MDowOjA6MDoxIiwic2Vzc2lvbklkIjpudWxsfSwiYXV0aGVudGljYXRlZCI6dHJ1ZSwicHJpbmNpcGFsIjp7ImVtcGlkIjo3MywiZW5hbWUiOiLmnajpl6vml60iLCJldXNlcm5hbWUiOiJ5eXgiLCJlcGFzcyI6IiQyYSQxMCROVnpJM1MwaG9QcjMzbkFmeTBNeWVlUU94YURiYTFiWmo4SjhFSldrU0s2L2RvVnF4Z2YycSIsInNleCI6IueUtyIsImhpcmVkYXRlIjoiMjAyMS0wNC0yOCIsImxlYXZlZGF0ZSI6IjIwMjEtMDQtMDQiLCJ0ZWwiOiIxODUzODE5OTIwMiIsInJvbGVpZCI6MSwic3RhdGUiOjAsImF1dGhvcml0aWVzIjpbeyJhdXRob3JpdHkiOiJST0xFX0FETUlOIn1dLCJlbmFibGVkIjp0cnVlLCJwYXNzd29yZCI6IiQyYSQxMCROVnpJM1MwaG9QcjMzbkFmeTBNeWVlUU94YURiYTFiWmo4SjhFSldrU0s2L2RvVnF4Z2YycSIsInVzZXJuYW1lIjoieXl4IiwiYWNjb3VudE5vbkV4cGlyZWQiOnRydWUsImFjY291bnROb25Mb2NrZWQiOnRydWUsImNyZWRlbnRpYWxzTm9uRXhwaXJlZCI6dHJ1ZX0sImNyZWRlbnRpYWxzIjpudWxsLCJuYW1lIjoieXl4In19.2e5cc6cWO4N6jBEcJlx2ff8s0uTY7bRxKNYusZoCqnQ74gQ7T2BGdbDS9pOIVzvYkRKHito3DWM-95AHYvQVHQ");
        System.out.println(claims);
    }
    private static final String ISS = "aaa";// jwt签发者
    private static final long EXP = 1000 * 60 * 60L; // jwt的过期时间，默认1个小时
    private static final String SECRET = "JAVA"; // 密钥

    public static String getToken(Authentication authentication){
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("auth",authentication);

        // username
        // 权限
        JwtBuilder builder = Jwts.builder()
                // 发布者
                .setIssuer(ISS)
                // 加密方式，密钥
                .signWith(SignatureAlgorithm.HS512, SECRET)
                // 超时时间
                .setExpiration(new Date(System.currentTimeMillis() + EXP))
                // 发布时间
                .setIssuedAt(new Date());
        String token = builder.addClaims(claims).compact();
        return token;
    }
    //获取解析后的token
    public static Claims getToken(String token){
        Jws<Claims> jws=Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token);
        return jws.getBody();
    }
    /*
    * 判断token是否过期
    * claims
    * */
    public static boolean isExpiration(Claims claims){
        Date expiration = claims.getExpiration();
        Date now=new Date();
        if(now.getTime()-expiration.getTime()>0){
            return false;
        }else {
            return true;
        }
    }
    //获取认证信息
    public static Map getAuth(Claims claims){
        Map auth = (Map) claims.get("auth");
        return auth;
    }




}
